package com.cyh.Aggregation_Trigger_Task_Interruptted_Handle;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

/**
 * Created by yanhuche on 3/15/2017.
 */
public class AggregationTask implements Runnable {

    private static final Logger LOGGER = Logger.getLogger(AggregationTask.class);

    private long reportRunningMilli = -1L;
    private int count = -1;

    @Override
    public void run() {
        reportRunningMilli = System.currentTimeMillis();
        count = 0;
        while (true) {
            if (reachNextRound()) {
                LOGGER.debug("Reach next round.");
                break;
            }

            count++;
            boolean isRunReportInAdaptationDone = runReportsForAdaptation();
            if (isRunReportInAdaptationDone) {
                LOGGER.debug("finished " + count);
            } else {
                LOGGER.error("finished with exception(s) " + count);
            }
        }
    }

    private boolean reachNextRound() {
        return TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())
                - TimeUnit.MILLISECONDS.toSeconds(reportRunningMilli) >= 10;
    }

    private boolean runReportsForAdaptation() {
        runReport();
        return true;
    }

    private void runReport() {
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        TimeoutTask timeoutTask = new TimeoutTask();
        Future<?> future = singleThreadExecutor.submit(timeoutTask);

        while (timeoutTask.taskStatus != TaskStatus.FINISHED) {
        }

        if (future != null) {
            future.cancel(true);
        }

    }

    class TimeoutTask implements Runnable {
        volatile TaskStatus taskStatus = TaskStatus.RUNNING;

        @Override
        public void run() {
            long sleepSecond = 6L;
            LOGGER.debug("sleepSecond: " + sleepSecond);
            try {
                TimeUnit.SECONDS.sleep(sleepSecond);
                taskStatus = TaskStatus.FINISHED;
            } catch (InterruptedException e) {
                LOGGER.warn("InterruptedException");
                taskStatus = TaskStatus.INTERRUPTED;
            }
        }
    }

    enum TaskStatus {
        RUNNING, INTERRUPTED, FINISHED
    }


}
